package com.object.utils;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.*;

import java.io.*;

/**
 *
 */
public class WordConvcePdfUtil
{

    public static void main(String[] argv)
    {
        //String pdfPath = argv[0];
        String pdfPath = "D:\\LiQingCode\\code\\demo\\src\\main\\resources\\static\\";
        BufferedOutputStream bos;
        try
        {
            //把word转pdf
            office2PDF(pdfPath + "word.docx", pdfPath + "word.pdf");
            //获取转换过后的pdf
            bos = new BufferedOutputStream(new FileOutputStream(new File(pdfPath + "bygh.pdf")));
            //传入我们转换过后的pdf 和 添加水印过后的pdf文件流
            setWatermark(bos, pdfPath + "word.pdf", "");
            //再删除转换过后的pdf
            (new File(pdfPath + "word.pdf")).delete();
            System.out.println("转换成功！");
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    public static FileInputStream convert(String pdfPath,String suffix, String fileName, String pdfName, String qzImg) throws FileNotFoundException
    {
        BufferedOutputStream bos = null;
        File file;
        try
        {
            //把word转pdf
            office2PDF(pdfPath + fileName + suffix, pdfPath + fileName + ".pdf");
            //获取转换过后的pdf
            file = new File(pdfPath + pdfName + ".pdf");
            if (!file.isFile())
            {
                file.createNewFile();
            }
            bos = new BufferedOutputStream(new FileOutputStream(file));
            //传入我们转换过后的pdf 和 添加水印过后的pdf文件流
            setWatermark(bos, pdfPath + fileName + ".pdf", qzImg);
            //再删除转换过后的pdf
            (new File(pdfPath + fileName + ".pdf")).delete();
            //   System.out.println("转换成功！");
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return new FileInputStream(pdfPath + pdfName + ".pdf");
    }

    public static int office2PDF(String sourceFile, String destFile)
    {
        try
        {
            File inputFile = new File(sourceFile);
            if (!inputFile.exists())
            {
                return -1;// 找不到源文件, 则返回-1
            }
            // 如果目标路径不存在, 则新建该路径
            File outputFile = new File(destFile);
            if (!outputFile.getParentFile().exists())
            {
                outputFile.getParentFile().mkdirs();
            }
            String OpenOffice_HOME = "C:\\Program Files (x86)\\OpenOffice 4\\";
            //这里是OpenOffice的安装目录, 在我的项目中,为了便于拓展接口,没有直接写成这个样子,但是这样是绝对没问题的
            // 如果从文件中读取的URL地址最后一个字符不是 '\'，则添加'\'
            if (OpenOffice_HOME.charAt(OpenOffice_HOME.length() - 1) != '\\')
            {
                OpenOffice_HOME += "\\";
            }
            // 启动OpenOffice的服务
            String command = OpenOffice_HOME
                    + "program\\soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\"";
            Process pro = Runtime.getRuntime().exec(command);
            // connect to an OpenOffice.org instance running on port 8100
            OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);
            // OpenOfficeConnection connection = new SocketOpenOfficeConnection("yourIP",8100);
            connection.connect();
            // convert
            DocumentConverter converter = new OpenOfficeDocumentConverter(
                    connection);
            converter.convert(inputFile, outputFile);
            // close the connection
            connection.disconnect();
            // 关闭OpenOffice服务的进程
            pro.destroy();
            return 0;
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return 1;
    }

    public static void setWatermark(BufferedOutputStream bos, String input, String qzImg) throws DocumentException, IOException
    {
        PdfReader reader = new PdfReader(input);
        PdfStamper stamper = new PdfStamper(reader, bos);
        int total = reader.getNumberOfPages() + 1;
        PdfContentByte content;
        BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
        //BaseFont base = BaseFont.createFont("/data/tmis/uploads/file/font/simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        PdfGState gs = new PdfGState();
        //  for (int i = 1; i < total; i++) {
        // content = stamper.getOverContent(i);// 在内容上方加水印
        content = stamper.getUnderContent(total - 1);// 在内容下方加水印
        gs.setFillOpacity(0.2f);
        // content.setGState(gs);
        content.beginText();
        content.setRGBColorFill(192, 192, 192);
        content.setFontAndSize(base, 50);
        content.setTextMatrix(100, 250);
        //水印图片
        InputStream path = new FileInputStream(qzImg);
        byte[] bytes = inputStream2byte(path);
        Image image = Image.getInstance(bytes);
        //位置
        image.setAbsolutePosition((300), (100)); // set the first background image of the absolute
        //设置水印图片的大小
        image.scaleToFit(150, 150);
        content.addImage(image);

        //    content.showTextAligned(Element.ALIGN_CENTER, "安徽省建筑工程质量第二监督检测站", 250, 400, 55);
        // content.showTextAligned(Element.ALIGN_CENTER,
        // "检测管理信息系统！",400,250, 55);
        content.setRGBColorFill(0, 0, 0);
        content.setFontAndSize(base, 8);
        content.endText();
        //    }
        stamper.close();
    }

    //input转byte[]
    public static byte[] inputStream2byte(InputStream inputStream) throws IOException
    {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inputStream.read(buff, 0, 100)) > 0)
        {
            byteArrayOutputStream.write(buff, 0, rc);
        }
        return byteArrayOutputStream.toByteArray();
    }
}
